<template>
  <c-select
    v-bind="$attrs"
    v-on="$listeners"
    v-loading="loading"
    element-loading-spinner="el-icon-loading"
    :value="value"
    :options="options"
    :props="props"
    @change="handleChange"
  ></c-select>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  components: {},
  model: {
    prop: 'value',
    event: 'select',
  },
  props: {
    value: String,
    searchParams: {
      type: Object,
      default: () => ({
        'loan_approval_status.eq': 3,
      }),
    },
    tableName: {
      type: String,
      default: 'customer_related',
    },
  },
  data() {
    return {
      defaultParams: {
        'gua_type.in': '2,4',
        groupFields: ['res_a', 'res_b'],
        fields: ['res_a', 'res_b', 'res_a_name', 'res_b_name'],
      },
      loading: false,
      props: {
        value: 'id',
        label: 'name',
      },
      options: [],
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {},
  created() {
    this.defaultParams['service_id.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, {
          ...this.searchParams,
          ...this.defaultParams,
        })
        .then(res => {
          const list = res?.data ?? []
          const temp = {}
          this.options = list.reduce((prev, curr) => {
            if (!temp[curr.res_a]) {
              temp[curr.res_a] = true
              prev.push({ id: curr.res_a, name: curr.res_a_name })
            }
            if (!temp[curr.res_b]) {
              temp[curr.res_b] = true
              prev.push({ id: curr.res_b, name: curr.res_b_name })
            }
            return prev
          }, [])
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleChange(val) {
      const item = this.options.find(it => it.id === val)
      this.$emit('select', val, item)
    },
  },
}
</script>

<style lang="scss" scoped></style>
